package com.sgai.zero_robot.utils;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;

import com.sgai.zero_robot.App;

public class BatteryHelper {
    private final String TAG = "BatteryHelper";
    private Context context;
    private BroadcastReceiver batteryReceiver;
    public int percent = -1;
    public boolean isCharging;
    private static class Holder {
        private static final BatteryHelper INSTANCE = new BatteryHelper();
    }

    public static BatteryHelper getInstance() {
        return BatteryHelper.Holder.INSTANCE;
    }
    private BatteryHelper() {
        this.context = App.APP.getApplicationContext();
    }

    // 启动监听（同时获取一次当前电量）
    public void start() {
        // 第一次直接获取当前电量
        IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent batteryStatus = context.registerReceiver(null, filter);
        if (batteryStatus != null) {
            printBatteryInfo(batteryStatus);
        }

        // 实时监听电量变化
        batteryReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                printBatteryInfo(intent);
            }
        };
        context.registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    }

    // 停止监听（防止内存泄漏）
    public void stop() {
        if (batteryReceiver != null) {
            context.unregisterReceiver(batteryReceiver);
            batteryReceiver = null;
        }
    }

    // 打印电量信息
    private void printBatteryInfo(Intent intent) {
        int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
        percent = (int) ((level / (float) scale) * 100);

        int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING
                || status == BatteryManager.BATTERY_STATUS_FULL;

        int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
        boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
        //电量：24%, 是否充电：true (USB: false, AC: false)
        LogUtil.d(TAG, "电量：" + percent + "%, 是否充电：" + isCharging +
                " (USB: " + usbCharge + ", AC: " + acCharge + ")");
    }
}

